package com.api.controller;

import com.api.mapper.EmigrationMapper;
import com.api.mapper.UserMapper;
import com.api.pojo.Emigration;
import com.api.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/emigration")
public class EmigrationController {

    @Autowired
    EmigrationMapper em;

    @Autowired
    UserMapper um;

    @RequestMapping("/create")
    public Map<String, Object> create(Emigration emigration) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        em.create(emigration);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/remove")
    public Map<String, Object> remove(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        em.remove(id);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/update")
    public Map<String, Object> update(Emigration emigration) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        if (emigration.getState() == 1) {
            User user = um.getById(emigration.getUid());
            user.setState(1);
            System.out.println(user);
            um.update(user);
        }
        em.update(emigration);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/get")
    public Map<String, Object> get(Integer pageNo, Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        pageNo = --pageNo * pageSize;
        List<Emigration> list = em.get(pageNo, pageSize);
        list.forEach(e -> {
            e.setUser(um.getById(e.getUid()));
            e.setExecutorUser(um.getById(e.getExecutor()));
        });
        map.put("data", list);
        map.put("total", em.count());
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
